package com.steakliu.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Component
@AllArgsConstructor
public class TokenValidateGatewayFilter extends AbstractGatewayFilterFactory {
    private static final String TOKEN = "token";
    private final ObjectMapper objectMapper;

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();
            if (request.getHeaders().getFirst(TOKEN) != null){
                return chain.filter(exchange);
            }
            response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeWith(Mono.create(monoSink -> {
                try {
                    byte[] bytes = objectMapper.writeValueAsBytes("token为空");
                    DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
                    monoSink.success(dataBuffer);
                }
                catch (JsonProcessingException jsonProcessingException) {
                    monoSink.error(jsonProcessingException);
                }
            }));
        };
    }
}
